<template>
  <div class="container">
    <!--工具栏-->
    <div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
      <el-form :inline="true" :model="filters" :size="size">
        <el-form-item label="学期">
          <el-select v-model="filters.termId" placeholder="请选择" clearable @change="loadQuestions">
            <el-option
              v-for="item in termOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    
    <div class="psych-test-container" v-if="questionList.length > 0">
      <h2 class="test-title">心理测评问卷</h2>
      <p class="test-desc">请根据您的真实感受，为每个问题选择最符合的选项。</p>
      
      <div v-if="hasCompleted" class="completed-notice">
        <el-alert
          title="您已完成本学期的心理测评"
          type="success"
          description="感谢您的参与，您可以查看您的得分结果。"
          show-icon
          :closable="false">
        </el-alert>
      </div>
      
      <div class="question-list">
        <div v-for="(question, index) in questionList" :key="question.id || index" class="question-item">
          <h3 class="question-title">
            <span class="question-num">{{ index + 1 }}.</span>
            {{ question.question }}
          </h3>
          <div class="options-container">
            <el-radio-group v-model="answers[index].score" :disabled="hasCompleted">
              <el-radio :label="10">完全符合</el-radio>
              <el-radio :label="8">比较符合</el-radio>
              <el-radio :label="6">一般符合</el-radio>
              <el-radio :label="4">较不符合</el-radio>
              <el-radio :label="2">不太符合</el-radio>
              <el-radio :label="0">完全不符合</el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>
      
      <div class="action-bar" v-if="!hasCompleted">
        <el-button type="primary" @click="submitAnswers" :loading="submitting">提交答案</el-button>
      </div>
      
      <div class="score-result" v-if="totalScore !== null">
        <h3>您的得分: {{ totalScore }}</h3>
      </div>
    </div>
    
    <div class="no-questions" v-else-if="filters.termId">
      <h3>当前学期尚未设置心理测评题目，请联系管理员。</h3>
    </div>
    
    <div class="no-term-selected" v-else>
      <h3>请选择学期进行心理测评</h3>
    </div>
  </div>
</template>

<script>
import { format } from "@/utils/datetime"
import BigNumber from 'bignumber.js'

export default {
  components:{},
  data() {
    return {
      size: 'small',
      filters: {
        termId: ''
      },
      termOptions: [],
      questionList: [],
      answers: [],
      submitting: false,
      totalScore: null,
      hasCompleted: false // 是否已完成答题
    }
  },
  methods: {
    // 获取学期下拉框选项
    getTermOptions: function (){
      this.$api.busTerm.findOptions(0).then(res => {
        this.termOptions = res.data
        // 设置当前学期
        this.getCurrentTerm()
      })
    },
    
    // 获取当前学期
    getCurrentTerm: function() {
      this.$api.busTerm.findCurrentTerm().then(res => {
        if(res.data && res.data.id) {
          this.filters.termId = res.data.id
          this.loadQuestions()
        }
      })
    },
    
    // 加载题目和已有答案
    loadQuestions: function() {
      if(!this.filters.termId) {
        this.questionList = []
        this.answers = []
        this.totalScore = null
        this.hasCompleted = false
        return
      }
      
      // 查询是否已有成绩
      this.$api.psyScore.findByCurrentUser(this.filters.termId).then(res => {
        if(res.code === 200 && res.data) {
          this.totalScore = res.data.totalScore
          // 如果有成绩，则表示已完成答题
          this.hasCompleted = true
        } else {
          this.hasCompleted = false
        }
      })
      
      // 获取当前用户的答题记录或题目列表
      this.$api.psyAnswer.findByCurrentUser(this.filters.termId).then(res => {
        if(res.code === 200) {
          const data = res.data || []
          
          // 如果返回的是PsyAnswer类型（答题记录）
          if(data.length > 0 && data[0].score !== undefined) {
            this.questionList = data.map(item => ({
              id: item.questionId,
              question: item.question,
              sortNum: item.sortNum
            }))
            
            // 按排序号排序
            this.questionList.sort((a, b) => a.sortNum - b.sortNum)
            
            // 设置答案
            this.answers = data.map(item => ({
              questionId: item.questionId,
              score: item.score ? Number(item.score) : 0
            }))
            
            // 计算总分
            this.calculateTotalScore()
          } 
          // 如果返回的是PsyQuestion类型（题目列表）
          else {
            this.questionList = data
            
            // 按排序号排序
            this.questionList.sort((a, b) => a.sortNum - b.sortNum)
            
            // 生成空答案
            this.answers = this.questionList.map(item => ({
              questionId: item.id,
              score: 0 // 默认分数为0
            }))
            
            if (!this.totalScore) {
              this.totalScore = null
            }
          }
        }
      })
    },
    
    // 计算总分
    calculateTotalScore: function() {
      if(!this.answers || this.answers.length === 0) {
        this.totalScore = null
        return
      }
      
      let total = 0
      this.answers.forEach(answer => {
        if(answer.score) {
          total += Number(answer.score)
        }
      })
      
      this.totalScore = total
    },
    
    // 提交答案
    submitAnswers: function() {
      if(this.hasCompleted) {
        this.$message.warning('您已完成本学期的心理测评，无法再次提交')
        return
      }
      
      if(this.questionList.length === 0 || this.answers.length === 0) {
        this.$message.error('没有可提交的题目!')
        return
      }
      
      if(this.questionList.length !== 10) {
        this.$message.error('题目数量不足，请联系管理员设置10道题目!')
        return
      }
      
      this.submitting = true
      
      // 准备提交的数据
      const submitData = this.answers.map((answer, index) => ({
        questionId: answer.questionId,
        score: answer.score
      }))
      
      // 提交答案
      this.$api.psyAnswer.saveAnswers(submitData, this.filters.termId).then(res => {
        this.submitting = false
        
        if(res.code === 200) {
          this.$message.success('提交成功!')
          // 设置为已完成状态
          this.hasCompleted = true
          // 重新加载数据
          this.loadQuestions()
        } else {
          this.$message.error('提交失败: ' + res.msg)
        }
      }).catch(err => {
        this.submitting = false
        this.$message.error('提交失败: ' + err.message)
      })
    }
  },
  mounted() {
    this.getTermOptions()
  }
}
</script>

<style scoped>
.psych-test-container {
  padding: 20px;
  margin-top: 60px;
}

.test-title {
  text-align: center;
  margin-bottom: 20px;
}

.test-desc {
  text-align: center;
  color: #666;
  margin-bottom: 30px;
}

.completed-notice {
  max-width: 800px;
  margin: 0 auto 30px;
}

.question-list {
  max-width: 800px;
  margin: 0 auto;
}

.question-item {
  margin-bottom: 30px;
  padding: 15px;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.question-title {
  margin-bottom: 15px;
}

.question-num {
  font-weight: bold;
  margin-right: 5px;
}

.options-container {
  padding: 10px 20px;
}

.el-radio {
  display: block;
  margin-left: 0;
  margin-bottom: 12px;
  line-height: 30px;
}

.action-bar {
  text-align: center;
  margin-top: 30px;
  margin-bottom: 20px;
}

.score-result {
  text-align: center;
  margin-top: 20px;
  padding: 15px;
  background-color: #f0f9eb;
  border-radius: 4px;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}

.no-questions, .no-term-selected {
  text-align: center;
  margin-top: 100px;
  color: #909399;
}
</style> 